<template>
  <div class="header">
    <div>
      <CustomerOrderQuery v-model:title='title' @queryClick="inquiry" @resettingClick = 'resetting' />
    </div>
    <div>
      <el-card >
        <template #header>
          <div class="customerTitle1">
            <span class="titleHead1">需求列表</span>
            <div >
              <VabButton
                @click="cancellation(3)"
                title="审核撤回"
              >

              </VabButton>
              <VabButton
                title="确认收货"
                plain
                type="primary"
                @click="cancellation(2)"
              >

              </VabButton>
              <VabButton
                title="需求取消"
                @click="cancellation(1)"
              >

              </VabButton>
            </div>
          </div>
        </template>
        <div>
          <el-table
            highlight-current-row
            v-loading="loading"
            ref="singleTableRef"
            :data="customer_order_list"
             height="300px"
            style="width: 100%"
            @current-change="handleSelectionChange"
            row-key="id"
            :tooltip-options="{ enterable: true, placement: 'top' }"
            tooltip-effect="dark"
          >
            <el-table-column width="40"  fixed="left">
              <template #default="scope">
                <label class="el-checkbox"
                       :class="{ 'is-checked': radioIndex && radioIndex.id === scope.row.id }"
                       @click="handleRadio(scope.row,$event)"
                >
                  <span class="el-checkbox__input" :class="{ 'is-checked': radioIndex && radioIndex.id == scope.row.id }"><span class="el-checkbox__inner"></span></span>
                </label>
              </template>
            </el-table-column>
            <el-table-column label="序号" width="60" align="center" fixed="left" show-overflow-tooltip>
              <template #default="props" >
                <div class="dropDownTab">
                  <span
                    v-text="(currentPage - 1) * pageSize + (props.$index + 1)"
                  ></span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="需求编号" align="center" width="150" fixed="left" show-overflow-tooltip>
              <template #default="scope">
               <span
                 @click="particulars(scope.row,$event)"
                 class="ellipsis textFont"
                 v-text="_FieldFormat(scope.row.order_no, '')"
               ></span>
              </template>
            </el-table-column>
            <el-table-column label="客户" align="center" min-width="230" show-overflow-tooltip>
              <template #default="scope">
               <span
                 style="text-align: left;"
                 class="ellipsis"
               >
                 {{_FieldFormat(scope.row.buyer_customer_name, '')}}
               </span>
              </template>
            </el-table-column>
            <el-table-column label="需求状态" align="center" width="130" show-overflow-tooltip>
              <template #default="scope">
               <span class="tagStatus" >
                  <el-tag @click="flowClick(scope.row.nodes)" class=" textFont">{{ scope.row.status_str || '--' }}</el-tag>
               </span>
              </template>
            </el-table-column>
            <el-table-column label="采购数量" align="center" width="80"  prop="sales_num" show-overflow-tooltip>
              <template #default="scope">
               <span
                 class="ellipsis numberMoney"

                 v-text="_FieldFormat(scope.row.buy_num || 0, '')"
               ></span>
              </template>
            </el-table-column>
            <el-table-column label="销售数量" align="center" width="80" prop="ordered_num" show-overflow-tooltip>
              <template #default="scope">
               <span
                 class="ellipsis numberMoney"
                 v-text="_FieldFormat(scope.row.ordered_num || 0, '')"
               ></span>
              </template>
            </el-table-column>
            <el-table-column label="出库数量" align="center" width="80" prop="actual_send_num" show-overflow-tooltip>
              <template #default="scope">
               <span
                 class="ellipsis numberMoney"
               >{{Number(scope.row.settle_num).toFixed(0) || 0}}</span>
              </template>
            </el-table-column>
            <el-table-column label="销售金额" align="center" width="120" prop="selling_price" show-overflow-tooltip>
              <template #default="scope">
               <span
                 class="ellipsis numberMoney"
               >
                 ￥{{ Number(scope.row.amount).toFixed(2) || '--' }}
               </span>
              </template>
            </el-table-column>
            <el-table-column label="销售员" align="center" width="100" show-overflow-tooltip>
              <template #default="scope">
               <span
                 class="ellipsis number"
               >
                 {{ scope.row.undertaker_name || '--' }}
               </span>
              </template>
            </el-table-column>
            <el-table-column label="客户下单时间" align="center" min-width="160" show-overflow-tooltip>
              <template #default="scope">
               <span
                 class="ellipsis number"
                 v-text="_FieldFormat(scope.row.create_at, 'time')"
               ></span>
              </template>
            </el-table-column>
            <el-table-column label="最新操作时间" align="center" min-width="160" show-overflow-tooltip>
              <template #default="scope">
               <span
                 class="ellipsis number"
               >{{ _FieldFormat(scope.row.update_at, 'time') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="订单取消时间" align="center" min-width="160" show-overflow-tooltip>
              <template #default="scope">
                 <span
                   class="ellipsis number">
                {{_FieldFormat(scope.row.cancel_time, 'time') || '--' }}
                 </span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="120" fixed="right">
              <template #default="{ row }">
                <el-button link  v-if="row.is_show_take" type="primary" @click="treatment_list(row,$event)">
                  承接
                </el-button>
                <el-button link v-else-if="row.is_show_handle" type="primary" @click="treatment_list(row,$event)">
                  去处理
                </el-button>
                <el-button link   v-else type="primary" @click="particulars(row,$event)">
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="customerPagination">
          <el-pagination
            background
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            layout="total, prev, pager, next,sizes, jumper"
            :page-sizes="[20, 50, 100, 200]"
            small="small"
            :total="count_number"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </div>
      </el-card>
      <el-card id="productId">
        <template #header>
          <div class="customerTitle1">
            <span class="leve2_title leave3Title titleHead1">产品信息<span class="title1"> <span v-if="saleOrderDetail" class="title2">需求编号</span>{{ saleOrderDetail?.order_no || ''}}</span></span>
          </div>
        </template>
        <div>
          <el-table	:tooltip-options="{ enterable: true, placement: 'top' }" tooltip-effect="dark"  :data="saleOrderDetail?.sale_order_detail"  max-height="300px">
            <el-table-column label="序号" align="center" width="60">
              <template #default="scope">
                <div class="table_style">
               <span style="margin-left: 5px" v-text=" (scope.$index + 1)"
               ></span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="订单编号" min-width="150" align="center"  show-overflow-tooltip>
              <template #default="scope">
             <span
               class="ellipsis "
               v-text="_FieldFormat(scope.row.order_id, '')"
             ></span>
              </template>
            </el-table-column>
            <el-table-column label="订单流转状态"  width="120" align="center"  show-overflow-tooltip>
              <template #default="scope">
             <span
               class="ellipsis"
               style="cursor: default"
             >{{ scope.row.order_status_str  || '--' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="销售组织"  width="210" align="center"  show-overflow-tooltip>
              <template #default="scope">
             <span
               class="ellipsis"
               v-text="_FieldFormat(scope.row.sales_org_name, '')"
             ></span>
              </template>
            </el-table-column>
            <el-table-column label="产品类型"  width="80" align="center" show-overflow-tooltip >
              <template #default="scope">
            <span
              class="ellipsis "
              v-text="_FieldFormat(scope.row.goods_type, '')"
            ></span>
              </template>
            </el-table-column>
            <el-table-column label="产品编码"  width="130" align="center" show-overflow-tooltip>
              <template #default="scope">
            <span
              class="ellipsis "
              v-text="_FieldFormat(scope.row.goods_no, '')"
            ></span>
              </template>
            </el-table-column>
            <el-table-column label="产品名称"  width="200" align="center" show-overflow-tooltip>
              <template #default="scope">
             <span
               v-text="_FieldFormat(scope.row.goods_name, '')"
             ></span>
              </template>
            </el-table-column>
            <el-table-column label="条码" align="center" width="150">
              <template #default="scope">
              <span
                class="ellipsis"
              >
              {{scope.row.barcode || '--'}}
             </span>
              </template>
            </el-table-column>
            <el-table-column label="规格型号"  width="80" align="center" show-overflow-tooltip>
              <template #default="scope">
            <span
              class="ellipsis "
              v-text="_FieldFormat(scope.row.spec_name, '')"
            ></span>
              </template>
            </el-table-column>
            <el-table-column label="销售数量"  width="80" align="center"  show-overflow-tooltip>
              <template #default="scope">
            <span
              class="ellipsis numberMoney"
            >{{ Number(scope.row.sales_num).toFixed(0) || '0' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="出库数量"  width="80" align="center" show-overflow-tooltip>
              <template #default="scope">
             <span
               class="ellipsis numberMoney"
             >
             {{ Number(scope.row.actual_qty).toFixed(0) || '0' }}
              </span>
              </template>
            </el-table-column>
            <el-table-column label="售后单号"  width="180" align="center" show-overflow-tooltip>
              <template #default="scope">
                 <span
                   v-for="(items,index) in  objectArray(scope.row.order_aftersale_uid)"
                   :key="index"
                   class="ellipsis textFont"
                   @click="serviceOrder(items)"
                 >
                         {{items || '--'}}
                       </span>
<!--                       <span
                         class="ellipsis textFont"
                         v-text="_FieldFormat(scope.row.order_aftersale_uid, '')"
                         @click="serviceOrder(scope.row.order_aftersale_uid)"
                       ></span>-->
              </template>
            </el-table-column>
            <el-table-column label="售后状态"  width="150" align="center">
              <template #default="scope">
                       <span
                         class="ellipsis "
                         v-text="_FieldFormat(scope.row.order_aftersale_status_text, '')"
                       ></span>
              </template>
            </el-table-column>

            <el-table-column label="批次号"  width="100" align="center" show-overflow-tooltip>
              <template #default="scope">
                       <span
                         class="ellipsis "
                         v-text="_FieldFormat(scope.row.batch_no, '')"
                       ></span>
              </template>
            </el-table-column>
            <el-table-column label="生产日期"  width="180" align="center" show-overflow-tooltip>
              <template #default="scope">
                       <span
                         class="ellipsis "
                         v-text="_FieldFormat(scope.row.product_date, '')"
                       ></span>
              </template>
            </el-table-column>
            <el-table-column label="有效期至"  width="180" align="center" show-overflow-tooltip>
              <template #default="scope">
                       <span
                         class="ellipsis "
                         v-text="_FieldFormat(scope.row.expire_date, '')"
                       ></span>
              </template>
            </el-table-column>
            <el-table-column label="仓库"  width="140" align="center" show-overflow-tooltip>
              <template #default="scope">
                       <span
                         class="ellipsis "
                         v-text="_FieldFormat(scope.row.warehouse_name, '')"
                       ></span>
              </template>
            </el-table-column>
            <el-table-column label="出库单号"  width="150" align="center" show-overflow-tooltip>
              <template #default="scope">
                       <span
                         class="ellipsis "
                         v-text="_FieldFormat(scope.row.stock_out_order_id, '')"
                       ></span>
              </template>
            </el-table-column>
            <el-table-column label="开票类型" align="center" width="150" show-overflow-tooltip>
              <template #default="scope">
                         <span
                           class="ellipsis number"
                           v-text="_FieldFormat(scope.row.invoice_type_str, '')"
                         ></span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>
    <FlowDialog ref="flowRef" />
    <TakeOver  ref="takeOver" @addressSubmit="addressSubmit" />
  </div>
</template>

<script setup lang="ts">

import router from "/@/router";
import {objectArray} from '../orderText'
import TakeOver from '../orderQuery/component/TakeOver.vue'
defineOptions({
  name: 'CustomerOrder',
})
import { ref } from "vue";
import CustomerOrderQuery from '../component/CustomerOrderQuery.vue'
import { DateFormat, FieldFormat } from "/@/utils/utils";
import {
  customerCancelAudit,
  customerOrderTrack,
  customerUndertake,
  customerUpdateStatus
} from "/@/api/dms/customerOrder";
import { ElMessage, ElMessageBox } from "element-plus";
import { orderCancel } from "/@/api/dms/order";
import FlowDialog from "/@/views/order_management/customer_order/component/FlowDialog.vue";
import {orderGroupCancelApproval} from "/@/api/dms/order/group";
const _FieldFormat = (value: string, type = '') => {
  return FieldFormat(value, type)
}
const saleOrderDetail = ref(undefined)
//确认收货
const takeOver = ref<any>(undefined)
const flowRef = ref<any>(undefined)
const title = ref('客户采购需求池')
const loading = ref(false)
const pageSize = ref(20)
const currentPage = ref(1)
const count_number = ref(0)
const customer_order_list = ref([])
const queryList = ref<any>({})
const singleTableRef = ref<any>(undefined)

// 单选
const radioIndex = ref<any>(undefined)
//分页
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getCustomerOrderList(queryList.value)
}
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getCustomerOrderList(queryList.value)
}
const getCustomerOrderList = async (value: object = {}, type = 0) => {
  loading.value = true
  await customerOrderTrack({ page: currentPage.value, pagesize: pageSize.value, ...value }).then((data: any) => {
    if (data.code == 200) {
      loading.value = false
      count_number.value = data.data.count
      customer_order_list.value = data.data.list
      saleOrderDetail.value = data.data.list[0]
      singleTableRef.value!.setCurrentRow(data.data.list[0])
      if (type == 1) {
        ElMessage.success(`查询成功`)
      } else if (type == 2) {
        ElMessage.success(`重置成功`)
      }
    }
  })
}
const treatment_list = (row: any,event:any) => {
  event.stopPropagation();
  if (row.is_show_take) {
    customerUndertake({ order_no: row.order_no, type: 1 }).then((data: any) => {
      if (data.code == 200) {
        router.push(`/order/treatment?path=1&id=${row.order_no}`)
      }
    })
  } else if (row.is_show_handle) {
    router.push(`/order/treatment?path=1&id=${row.order_no}`)
  }

}
// 单选
const handleRadio = (row: any,event:any) => {
  event.stopPropagation();
  // radioIndex.value = row
  if (radioIndex.value && radioIndex.value.order_no == row.order_no  )  {
    radioIndex.value = undefined
    return
  }
  radioIndex.value = row
}
const a = ref(1)
// 选择
const handleSelectionChange = (val: any, va: any) => {
  saleOrderDetail.value = val
 /* document
    .getElementById('productId')
    ?.scrollIntoView({ behavior: 'instant', block: 'end' })*/
}
// *******新建****************
const create = () => {
  router.push('/order/addOrder?path=2')
}
// 售后订单跳转
const serviceOrder =(va:any)=>{
  if(va != null && va !=''){
    router.push(`/sales/salesDetails?path=2&uid=${va}`)
  }
}

// 查询重置
const inquiry = (va: any) => {
  const data = {
    state: va.state.toString(),//状态，
    product_code: va.product_code.toString(),// 产品
    product_name: va.product_name.toString(),// 产品名称
    start_time: va.time && DateFormat(va.time[0], 'YYYY-MM-DD'),//时间
    end_time: va.time && DateFormat(va.time[1], 'YYYY-MM-DD'),
    order_no: va.order_no.toString(),// 采购号
    buyer_customer_id: va.buyer_customer_id.toString(),// 客户id
    order_price_start: va.order_price_start,
    order_price_end: va.order_price_end,
    sales_org_id: va.sales_org_id.toString(),//销售组织
    undertaker_name: va.undertaker_name.toString(),//销售员id
    order_state: va.order_state.toString(),//订单流转状态
    order_num: va.order_num,//订单编号
    barcode:va.barcode.toString(),
  }
  queryList.value = { ...queryList.value, ...data }
  currentPage.value = 1
  pageSize.value = 20
  getCustomerOrderList(data, 1)
}
const resetting = (va: any) => {
  const data = {
    state: va.state.toString(),//状态，
    product_code: va.product_code.toString(),// 产品
    product_name: va.product_name.toString(),// 产品
    start_time: va.time && DateFormat(va.time[0], 'YYYY-MM-DD'),//时间
    end_time: va.time && DateFormat(va.time[1], 'YYYY-MM-DD'),
    order_no: va.order_no.toString(),// 采购号
    buyer_customer_id: va.buyer_customer_id.toString(),// 客户id
    order_price_start: va.order_price_start,//金额开始
    order_price_end: va.order_price_end,//金额结束
    sales_org_id: va.sales_org_id.toString(),//销售组织
    undertaker_name: va.undertaker_name.toString(),//销售员id
    order_state: va.order_state.toString(),//订单流转状态
    order_num: va.order_num,//订单编号
    barcode:va.barcode.toString(),
  }
  queryList.value = { ...queryList.value, ...data }
  currentPage.value = 1
  pageSize.value = 20
  getCustomerOrderList(data, 2)
}
const statusType = (va: any) => {
  if (va == 112) {
    return '已保存'
  } else if (va == 111) {
    return '草稿'
  } else if (va == 113) {
    return '待审核'
  } else if (va == 2) {
    return '已取消'
  } else if (va == 3) {
    return '已完成'
  } else if (va == 100) {
    return '待接收'
  } else if (va == 110) {
    return '已接收'
  } else if (va == 120) {
    return '待客户确认'
  } else if (va == 130) {
    return '客户已确认'
  } else if (va == 150) {
    return '订单已付款'
  } else if (va == 160) {
    return '已出库'
  } else if (va == 170) {
    return '已发出'
  } else if (va == 180) {
    return '部分出库'
  } else if (va == 190) {
    return '部分发出'
  } else {
    return '--'
  }
}
const cancellation = (value: any) => {
  // console.log(radioIndex.value.order)  if (radioIndex.value && radioIndex.value.status != '2') {
  if(radioIndex.value){
    if (value == 1) {
      ElMessageBox.confirm(
        `订单取消后无法执行后续操作，请确认是否取消 需求编号为：${radioIndex.value.order_no}的订单。`,
        {
          confirmButtonText: '确定',
          cancelButtonText: '返回',
          type: 'warning',
        }
      )
        .then(() => {
          customerUpdateStatus({ order_no: radioIndex.value.order_no, status: 2 }).then((data: any) => {
            if (data.code == 200) {
              ElMessage.success(`取消成功`)
              radioIndex.value = undefined
              getCustomerOrderList(queryList.value)
            }
          })
        })
    } else if (value == 2) {
      if (radioIndex.value && radioIndex.value.status_str == '已发出'||  radioIndex.value.status_str == '部分发出') {
        takeOver.value.openUp = true
        takeOver.value.uid = radioIndex.value.order_no
        takeOver.value.type = 2
      } else if(radioIndex.value && radioIndex.value.status_str == '已完成'){
        ElMessage({
          message: '已完成的订单无需再次进行确认收货',
          type: 'warning',
        })
      }else {
        ElMessage({
          message: '该订单状态不允许确认收货',
          type: 'warning',
        })
      }

    }else if(value == 3){
      ElMessageBox.confirm(
        `订单审核撤回后无法执行后续操作，请确认是否撤回 需求编号为：${radioIndex.value.order_no || '--'}的订单。`,
        {
          confirmButtonText: '确定',
          cancelButtonText: '返回',
          type: 'warning',
        }
      )
        .then(() => {
          orderGroupCancelApproval({uid:radioIndex.value.order_no}).then((data:any)=>{
            if (data.code == 200){
              radioIndex.value = undefined
              ElMessage.success(`审核撤回成功`)
              getCustomerOrderList(queryList.value)
            }
          })
        })
    }
  } else {
    ElMessage({
      message: '请先选择订单',
      type: 'warning',
    })
  }
}
//详情
const particulars = (row: any,event:any) => {
  event.stopPropagation();
  localStorage.setItem('orderPath2','1')
  router.push(`/order/treatment?path=2&id=${row.order_no}`)
}
// 订单排序
const sortList = (column: any, prop: any, order: any) => {
  if (column.order == null || column.order == "descending") {
    queryList.value = { ...queryList.value, sort_field: column.prop, sort: 'asc' }
    getCustomerOrderList(queryList.value)
  } else if (column.order == "ascending") {
    queryList.value = { ...queryList.value, sort_field: column.prop, sort: 'desc' }
    getCustomerOrderList(queryList.value)
  }

}
//流程图
const flowClick = (va: any) => {
  flowRef.value.open(va)
}
//确认收货地址
const addressSubmit = (va: any) => {
  radioIndex.value = undefined
  getCustomerOrderList(queryList.value)

}
onActivated(() => {
  getCustomerOrderList(queryList.value)
  radioIndex.value = undefined
})
</script>

<style lang="scss" scoped>
@import "../index";

.tabStyle {
  :deep() {
    .el-table__expanded-cell {
      padding: 0px;
    /*  .el-table__row{
        background-color: rgba(250, 250, 250,1) !important;
      }
      .is-leaf {
        background-color: rgba(230, 242, 255,1)  !important;
      }*/
    }

  }
/*  .tabTh {
    padding-left: 49px;
    position:relative;
    :deep() {
      .el-table__body-wrapper {
        overflow: hidden;
      }
    }
    !* &:before
     {
       content:"";
       position: absolute;
       top:-10px;
       left: 83px;
       border-style: solid;
       border-width: 0 6px 10px 6px;
       border-color: transparent transparent #f6f6f6 transparent;
     }*!
  }*/
}

.dropDownTab{
  text-align: center;
  position: relative;
 /* .dropDownTab1{
    position: absolute;
    top: 3px;
    right: -5px;
    cursor: pointer;
  }*/
}
</style>
